<?php
if (!function_exists('fnmatch')) {
	function fnmatch($pattern, $string) {
		for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
			switch ($c = $pattern[$n]) {
				case '\\':
					$npattern .= '\\' . @$pattern[++$n];
					break;
				case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
					$npattern .= '\\' . $c;
					break;
				case '?': case '*':
					$npattern .= '.' . $c;
					break;
				case '[': case ']': default:
					$npattern .= $c;
				if ($c == '[') {
					$op++;
				} else if ($c == ']') {
					if ($op == 0) return false;
					$op--;
				}
				break;
			}
		}		
		if ($op != 0) return false;
		
		return preg_match('/' . $npattern . '/i', $string);
	}
}

$localfolder = $argv[1];
$logfile = "log.txt";

$print_file_counts=true;//this can help you find new templates that have not been translated!

$hash_list = array();//The md5 sums mapped to translations

$hash_list_file = array();//The md5 sums mapped to translations
$order   = array("\r\n", "\n", "\r");
$endline ="\r";

$header = "msgid \"\"
	msgstr \"\"
	\"Project-Id-Version: AthenaOne\\n\"
	\"POT-Creation-Date: \\n\"
	\"PO-Revision-Date: \\n\"
	\"Last-Translator: \\n\"
	\"Language-Team: \\n\"
	\"MIME-Version: 1.0\\n\"
	\"Content-Type: text/plain; charset=utf-8\\n\"
	\"Content-Transfer-Encoding: 8bit\\n\"";


$file_word_count = array();// for recording what files have been translated and how may items where in each file
$supportedLanguage = array('vi_VN','en_US');
$defaultLang = 'vi_VN';


/*
 if (!file_exists('languages')) {
 mkdir('languages');	
 foreach ( $supportedLanguage as $value ) {
 mkdir("languages/$value");
 mkdir("languages/$value/common");		
 }       
 }		
 */
$rootfolder = realpath(dirname(__FILE__). '/..');

if (!file_exists($rootfolder."/$localfolder/languages/$defaultLang")) {
	mkdir($rootfolder."/$localfolder/languages/$defaultLang",0777,true);
}

/////////////load key of current file/////
$outFile = realpath(dirname(__FILE__). '/..') ."/$localfolder/languages/$defaultLang/default.po";
$rootFile = realpath(dirname(__FILE__). '/..') ."/local/languages/$defaultLang/default.po";
$rootFile1 = realpath(dirname(__FILE__). '/..') ."/$localfolder/languages/$defaultLang/default.po";


if (file_exists($rootFile)) {
	
	$fh = fopen($rootFile, 'r') or die("can't open file");	
	
	$patterngetkey = '!msgid[\s]+["](.*?)["][\s]*msgstr!s';
	if (filesize($rootFile) >0) {
		$currentcontent = fread($fh, filesize($rootFile));
		preg_match_all($patterngetkey, $currentcontent, $matcheskey);
		
		foreach($matcheskey[1] as $mkey) {
			$newmkey = str_replace($order, $endline, $mkey);
			$mymd5 = md5($newmkey);
			$hash_list_old[$mymd5]= $newmkey;	
			
		}
	}
	fclose($fh);
	
}

if (file_exists($rootFile1)) {
    
    $fh = fopen($rootFile1, 'r') or die("can't open file");  
    
    $patterngetkey = '!msgid[\s]+["](.*?)["][\s]*msgstr!s';
    if (filesize($rootFile1) >0) {
        $currentcontent = fread($fh, filesize($rootFile1));
        preg_match_all($patterngetkey, $currentcontent, $matcheskey);
        
        foreach($matcheskey[1] as $mkey) {
            $newmkey = str_replace($order, $endline, $mkey);
            $mymd5 = md5($newmkey);
            $hash_list_old[$mymd5]= $newmkey;   
            
        }
    }
    fclose($fh);
    
}
//////////////////////////////////////////

$scanFolder = array('controllers','ordo','includes','templates');
$flog = fopen($logfile, 'w') or die("can't open file");
//grep static text only
$regexphp = '!L10nHelper\:\:[_][(][\'"](.*?)[\'"][,)]!s';
$regexhtml = '!{translate[\sa-zA-Z0-9$=\-\>\(\)\'_]*}(.*?){/translate}!s';
$regexviewpath = '!\$this-\>\view-\>path(\s?)[=](\s?)[\'"](.*?)[\'"]!s';
$patterncheckescape = "![\\\][\"]!s";
$patterncheckescape1 = "![\"]!s";
$hash_list = array();
$comment_hash_list= array();
$pattern = $regexphp;
foreach ( $scanFolder as $folder ) {
	echo realpath(dirname(__FILE__). '/..') ."/$localfolder/$folder\n";
	if (!file_exists(realpath(dirname(__FILE__). '/..') ."/$localfolder/$folder")) {
		continue;
	}
	$file_list=list_directory(realpath(dirname(__FILE__). '/..') ."/$localfolder/$folder");
	
	foreach($file_list as $file){
		//ignore svn file		
		$path_info = pathinfo($file);
		$ext =    	$path_info['extension'];
		if (fnmatch('*.svn-base',$file) 
				||(($ext != 'php')&&($ext != 'html'))) {
			continue;
		}
		
		if ($ext == 'php') {
			$pattern = $regexphp;
		} else if ($ext == 'html') {
			$pattern = $regexhtml;
		}
		if(filesize($file)==0){
			//do nothing with this file!	
			fwrite($flog, "(IGNORED EMPTY FILE) File name : ".$file."\n");
			
		}else{
			fwrite($flog, "File name : ".$file."\n");
			
			$fp = fopen($file, 'r');
			$content = fread($fp, filesize($file));
			
			
			
			preg_match_all($pattern, $content, $matches);		
			//	echo "matching $file \n";		
			foreach($matches[1] as $m) {
				preg_match_all($patterncheckescape,$m,$matchesEscape);
				preg_match_all($patterncheckescape1,$m,$matchesEscape1);
				if (count($matchesEscape[0]) == 0 && count($matchesEscape1[0]) > 0) {
					$m1 = addslashes($m);
					fwrite($flog, "add slashes : file name[$file] \n original [$m] \n modified [$m1]\n");
					echo  "add slashes : file name[$file] \n original [$m] \n modified [$m1]\n";
				} else {
					$m1 = $m;
				}
				
				$newmkey = str_replace($order, $endline, $m1);			
				
				$mymd5 = md5($newmkey);
				if(!array_key_exists($mymd5,$hash_list)){
					if (isset($hash_list_old) && array_key_exists($mymd5,$hash_list_old)) {
						continue;
						
					} else {
						//$hash_list[$mymd5]= '';				
						$hash_list[$mymd5]= $newmkey;
						$countwordsinphp += 1;	
						fwrite($flog, "Add new key: [$mymd5][$newmkey] \n");
					}			
					
					
				}	
				$comment_hash_list[$mymd5][$file] = "Folder : [$folder] File :[".$file."]";
				
			}
		}
	}	
}

fclose($flog);
//out put to file
//todo $hash_list access by index

if (file_exists($outFile)) {
	$fh = fopen($outFile, 'a') or die("can't open file");
	if (filesize($outFile) ==0) {
		$stringData =  $header."\n\n";
	}
} else {
	
	$fh = fopen($outFile, 'w') or die("can't open file");
	$stringData =  $header."\n\n";
	
}
$countnum = 1;	
foreach($hash_list as $hash => $word){
	
	$listfilename = $comment_hash_list[$hash];
	$stringData.="### num:$countnum, key: [$word] appear in files: ### \n";
	if ($listfilename != null) {
		foreach ( $listfilename as $value ) {				     
			$stringData.="# $value \n";
		}
	}	
	$stringData.="msgid \"".$word."\"\n";
	$stringData.="msgstr \"".$word."\"\n\n";			
	
	$countnum +=1;
	
	
}	


fwrite($fh, $stringData);
fclose($fh);
//write to log file
$total = $countwordsinphp + $countwordsintemp;


//$file_word_count[$file]=count($matches[1]);// how many words where in this file


function list_directory($dir) {
	$file_list = '';
	$stack[] = $dir;
	while ($stack) {
		$current_dir = array_pop($stack);
		if ($dh = opendir($current_dir)) {
			while (($file = readdir($dh)) !== false) {
				if ($file !== '.' AND $file !== '..') {
					$current_file = "{$current_dir}/{$file}";
					if (is_file($current_file)) {						
						$file_list[] = "{$current_dir}/{$file}";
					} elseif (is_dir($current_file)) {
						$stack[] = $current_file;
					}
				}
			}
		}
	}
	return $file_list;
}
?>
